import { useState, useEffect } from "react";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import ListItem from "@mui/material/ListItem";
import ButtonGroup from "@mui/material/ButtonGroup";
import Grid from "@mui/material/Grid";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import DualList from "./DualList";
import DualListPart from "./DualListPart";
import CopyToClipboard from "react-copy-to-clipboard";
import cacheApis from "../apis/caches.mjs";
import { downCache } from "../utilities.mjs";
import { GM_registerMenuCommand } from "tm";
import { titleFont, firstDlg, codeStyle } from "../data.mts";

export default function CacheDialog(properties: { inner?: HTMLElement }) {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<Record<string, Record<string, Blob>>>({});
  const [summary, setSummary] = useState("");

  const updateData = async () => {
    try {
      const result_1 = await cacheApis.query();
      setData(result_1.data);
      setSummary(cacheApis.summary(result_1));
      return Object.keys(result_1.data).length > 0;
    } catch {
      setOpen(false);
    }
  };

  useEffect(() => {
    updateData()
      .then((have) => {
        if (have) {
          GM_registerMenuCommand("Cache UI", () => {
            setOpen(true);
          });
        }
      })
      .catch(() => {
        setOpen(false);
      });
  }, []);

  const clean = (type: 1 | 2 | 3) => {
    cacheApis
      .clear(type)
      .then(() => {
        void updateData();
      })
      .catch(() => {
        alert("清空失败");
        void updateData();
      });
  };

  return (
    <Dialog
      open={open}
      onClose={() => {
        setOpen(false);
      }}
      sx={firstDlg}
      container={properties.inner}
    >
      <DialogTitle sx={titleFont}>离线缓存列表</DialogTitle>
      <DialogContent
        sx={{
          display: "flex",
          flexDirection: "column",
        }}
      >
        <Card sx={{ mb: "5px", height: "max-content" }}>
          <CardContent
            sx={{
              p: "6px",
              m: "8px",
            }}
          >
            <pre style={codeStyle}>
              <code>{summary}</code>
            </pre>
          </CardContent>
          <CardActions
            sx={{
              p: "8px",
              pt: 0,
            }}
          >
            <Button
              size="small"
              color="error"
              onClick={() => {
                clean(1);
              }}
            >
              清理缓存
            </Button>
            <Button
              size="small"
              color="error"
              onClick={() => {
                clean(2);
              }}
            >
              卸载服务
            </Button>
            <Button
              size="small"
              color="error"
              onClick={() => {
                clean(3);
              }}
            >
              清理并卸载
            </Button>
          </CardActions>
        </Card>
        <DualList>
          {Object.keys(data).map((skey) => (
            <DualListPart key={"s" + skey} header={skey}>
              {Object.keys(data[skey]).map((url) => (
                <ListItem key={url}>
                  <Grid
                    container
                    direction="row"
                    justifyContent="space-between"
                    alignItems="center"
                    spacing={2}
                  >
                    <Grid
                      size="grow"
                      sx={{
                        display: "flex",
                        justifyContent: "center",
                      }}
                    >
                      <code style={codeStyle}>{url}</code>
                    </Grid>
                    <Grid
                      size={5}
                      sx={{
                        display: "flex",
                        justifyContent: "center",
                      }}
                    >
                      <ButtonGroup orientation="vertical">
                        <Button
                          onClick={() => {
                            downCache(data[skey][url], url);
                          }}
                          sx={{ fontSize: 11 }}
                        >
                          下载
                        </Button>
                        <CopyToClipboard text={url}>
                          <Button sx={{ fontSize: 11 }}>复制地址</Button>
                        </CopyToClipboard>
                      </ButtonGroup>
                    </Grid>
                  </Grid>
                </ListItem>
              ))}
            </DualListPart>
          ))}
        </DualList>
      </DialogContent>
    </Dialog>
  );
}
